﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.DataConvert.model;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Controls;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Collections;
using PlanningGIS.Util.Convertor;
using PlanningGIS.ArcGIS;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Util.Win32;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Log;
using PlanningGIS.MapSheet;
using PlanningGIS.Framework.Config;

namespace PlanningGIS.DataConvert.form
{
    /// <summary>
    ///作用：矢量数据导出界面
    /// </summary>
    public partial class FrmDlgDataExport : Office2007Form
    {
        /// <summary>
        /// 
        /// </summary>
        private IMap m_pMap;
        /// <summary>
        /// 
        /// </summary>
        private IApplication m_Application = null;
        /// <summary>
        /// 自定义导出范围图形
        /// </summary>
        private IPolygon pPolygonCustom; 
        /// <summary>
        /// 按测区范围
        /// </summary>
        private IPolygon pPolygonSurvey;
        /// <summary>
        /// 
        /// </summary>
        private IElement m_pElementUserDraw;
        /// <summary>
        /// 
        /// </summary>
        private DlgDataExportConstruct dlgDataExportConstruct;
        /// <summary>
        /// 
        /// </summary>
        private DlgDataExport dlgDataExport;
        /// <summary>
        /// 是否正在导出中
        /// </summary>
        private bool doing = false;
        /// <summary>
        /// 是否被用户终止
        /// </summary>
        private bool breaked = false;
        /// <summary>
        /// 
        /// </summary>
        private SelectXZQ selectXZQ1 = null;
        /// <summary>
        /// 实现窗体的单态，每次弹出的窗口都为同一个
        /// </summary>
        private static FrmDlgDataExport dlgDataExportForm;
        /// <summary>
        /// 树动
        /// </summary>
        private bool tree = false; 
        /// <summary>
        /// 表动
        /// </summary>
        private bool grid = false; 
        /// <summary>
        /// 
        /// </summary>
        private string ruleName;    

        /// <summary>
        /// 构造类
        /// </summary>
        /// <param name="value"></param>
        public FrmDlgDataExport(IApplication value)
        {
            InitializeComponent();

            m_Application = value;
            if (m_Application != null && (m_Application.Document as IMxDocument ).ActiveView.FocusMap !=null)
            {

                m_pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;

            }
        }

        /// <summary>
        /// 获取单态对象
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static FrmDlgDataExport GetDlgExportForm(IApplication value)
        {
            if (dlgDataExportForm == null)
            {
                dlgDataExportForm = new FrmDlgDataExport(value);
            }

            return dlgDataExportForm;
        }

        #region 事件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_Load(object sender, EventArgs e)
        {

            cboType.SelectedIndex = 0;
            dataGridViewByMap.ColumnHeaderMouseClick += ControlHelper.dataGridViewX_ColumnHeaderMouseClick;

            //图幅选择控件赋控制器
            IHookHelper m_HookHelp = new HookHelperExClass();
            m_HookHelp.Hook = m_Application;
            chooseTuFu2.HookHelper = m_HookHelp;
            chooseFWX2.HookHelper = m_HookHelp;
            chooseFWX2.selectAreaControl1.afterButtonOkShift1 += new AfterButtonOkShift(AfterButtonOkEvent);

            //自定义范围选择控件
            selectAreaControl2.afterButtonOkShift1 = new AfterButtonOkShift(AfterButtonOkEvent);
            selectAreaControl2.HookHelper = m_HookHelp;

            //刷新按地图导出树控件
            RefreshCurMapLayer();

            string logPanelName = "日志";
            (m_Application as IFramework).DockManager.ActivateDockPanel(logPanelName);

            this.selectXZQ1 = new SelectXZQ();
            // 
            // tabControlPanel10
            // 
            this.tabControlPanel10.Controls.Add(this.selectXZQ1);
            this.tabControlPanel10.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControlPanel10.Location = new System.Drawing.Point(0, 26);
            this.tabControlPanel10.Name = "tabControlPanel10";
            this.tabControlPanel10.Padding = new System.Windows.Forms.Padding(1);
            this.tabControlPanel10.Size = new System.Drawing.Size(307, 457);
            this.tabControlPanel10.Style.BackColor1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(142)))), ((int)(((byte)(179)))), ((int)(((byte)(231)))));
            this.tabControlPanel10.Style.BackColor2.Color = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(237)))), ((int)(((byte)(254)))));
            this.tabControlPanel10.Style.Border = DevComponents.DotNetBar.eBorderType.SingleLine;
            this.tabControlPanel10.Style.BorderColor.Color = System.Drawing.Color.FromArgb(((int)(((byte)(59)))), ((int)(((byte)(97)))), ((int)(((byte)(156)))));
            this.tabControlPanel10.Style.BorderSide = ((DevComponents.DotNetBar.eBorderSide)(((DevComponents.DotNetBar.eBorderSide.Left | DevComponents.DotNetBar.eBorderSide.Right)
                        | DevComponents.DotNetBar.eBorderSide.Bottom)));
            this.tabControlPanel10.Style.GradientAngle = 90;
            this.tabControlPanel10.TabIndex = 3;
            // 
            // selectXZQ1
            // 
            this.selectXZQ1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.selectXZQ1.Location = new System.Drawing.Point(1, 1);
            this.selectXZQ1.Name = "selectXZQ1";
            this.selectXZQ1.Size = new System.Drawing.Size(305, 20);
            this.selectXZQ1.TabIndex = 0;
            selectXZQ1.HookHelper = m_HookHelp;
            #region ToolTips
            SuperTooltip spttUseGP = new SuperTooltip();
            spttUseGP.SetSuperTooltip(this.chkUseGP,
                new SuperTooltipInfo("利用GP工具进行导出，速度较快，但日志和进度条不够详细，且仅支持导出格式为SHP、MDB和GDB。\r\n注意：同一个要素类只能被导出一次！", "", "", null, null, eTooltipColor.Office2003));

            SuperTooltip spttDelNull = new SuperTooltip();
            spttDelNull.SetSuperTooltip(this.chkDelNullData,
                new SuperTooltipInfo("导出完毕后，自动删除无要素图层，且仅支持导出格式为SHP、MDB和GDB。", "", "", null, null, eTooltipColor.Office2003));

            #endregion

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!(m_Application as IFramework).IsMapCtrlactive)
            {
                MsgHelper.ShowInfomationMsgbox("请先切换到数据视图再进行此操作！");
                e.Cancel = true;
            }

            if (doing)
            {
                MsgHelper.ShowInfomationMsgbox("导出还未结束，不能退出该窗口！");
                e.Cancel = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_FormClosed(object sender, FormClosedEventArgs e)
        {
            (m_Application as IFramework).Tool = null;
            chooseTuFu2.ClearElements();
            //chooseXZQ1.ClearElements();

            IActiveView pAV = (m_Application.Document as IMxDocument).ActiveView;

            IGraphicsContainer pGeoContainer = pAV as IGraphicsContainer;

            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                    //IActiveView pAV = ((AxMapControl)statusController.Host).ActiveView;
                    pAV.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pAV.Extent);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            dlgDataExportForm = null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            #region 定义变量
            List<IFeatureClass> pFeatClsesTarget = new List<IFeatureClass>();
            List<IFeatureClass> pFeatClses = new List<IFeatureClass>();
            List<string> targetFeatCLsNames = new List<string>();
            List<string> whereClauses = new List<string>();

            //FrmNewLog frmNewLog = new FrmNewLog(OperateType.DataExport);

            dataGridViewByMap.Refresh();

            #endregion

            try
            {
                #region 条件判断
                if (!(m_Application as IFramework).IsMapCtrlactive)
                {

                    MsgHelper.ShowInfomationMsgbox("请先切换到数据视图再进行此操作！");
                    return;
                }

                if (txtExportPath.Text == "")
                {
                    MsgHelper.ShowInfomationMsgbox("请选择导出路径！");
                    return;
                }

                if (!AnyLayerChecked())
                {
                    MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
                    return;
                }

                if (!chkAll.Checked)
                {
                    switch (tabControl2.SelectedTab.Text)
                    {
                        case "按图幅范围": //按图幅导出
                            if (chooseTuFu2.TuFus == null || chooseTuFu2.TuFus.Count == 0)
                            {
                                MsgHelper.ShowInfomationMsgbox("未选择图幅！");
                                return;
                            }
                            break;
                        case "按自定义范围": //按自定义范围
                            if (pPolygonCustom == null)
                            {
                                MsgHelper.ShowInfomationMsgbox("未划定范围！");
                                return;
                            }
                            break;

                        case "按测区范围":
                            pPolygonSurvey = chooseFWX2.PolygonFWX;
                            if (pPolygonSurvey == null)
                            {
                                MsgHelper.ShowInfomationMsgbox("未选择测区！");
                                return;
                            }
                            break;

                        case "按行政区范围":
                            pPolygonSurvey = selectXZQ1.GetGeometry() as IPolygon;
                            if (pPolygonSurvey == null)
                            {
                                MsgHelper.ShowInfomationMsgbox("未选择行政区！");
                                return;
                            }
                            break;
                        default:
                            return;
                    }
                }
                #endregion

                #region 初始化参数
                for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                    {
                        IFeatureLayer pFeatLyr = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;

                        pFeatClses.Add(pFeatLyr.FeatureClass);
                        targetFeatCLsNames.Add(StringHelper.ConvertWRTNull(dataGridViewByMap.Rows[i].Cells[2].Value) != "" ?
                            StringHelper.ConvertWRTNull(dataGridViewByMap.Rows[i].Cells[2].Value) : ((dataGridViewByMap.Rows[i].Tag as IFeatureLayer).FeatureClass as IDataset).Name);

                        //ILayerGeneralProperties pLayerGeneralProperties = pFeatLyr as ILayerGeneralProperties;
                        //string lyrDescription = pLayerGeneralProperties.LayerDescription;

                        whereClauses.Add(StringHelper.ConvertWRTNull(dataGridViewByMap.Rows[i].Cells[3].Value));
                    }
                }
                #endregion

                #region 显示进度条和终止按钮
                progressBarSub.Visible = true;
                progressBarAll.Visible = true;
                btnCancel.Visible = true;
                #endregion

                #region 判断导出数据的类型
                zjgisWorkspaceType workspaceType;
                switch (cboType.SelectedIndex)
                {
                    case 0:
                        workspaceType = zjgisWorkspaceType.gdb;
                        break;

                    case 1:
                        workspaceType = zjgisWorkspaceType.mdb;
                        break;

                    case 2:
                        workspaceType = zjgisWorkspaceType.shp;
                        break;

                    //case 3:
                    //    ExportE00();
                    //    return;
                    case 3:
                        ExportDwg();
                        return;
                    //case 5:
                    //    ExportMif();
                    //    return;
                    default:
                        return;
                }
                #endregion

                if (tabControl2.SelectedTab.Text == "按图幅范围" && chkEpByTufu.Checked)
                {
                    #region 按图幅分幅导出
                    foreach (Mapsheet tuFu in chooseTuFu2.TuFus)
                    {
                        if (breaked) break;

                        dlgDataExportConstruct = new DlgDataExportConstruct();
                        dlgDataExportConstruct.FeatClsListSource = pFeatClses;
                        dlgDataExportConstruct.TargetFeatClsNames = targetFeatCLsNames;
                        dlgDataExportConstruct.WhereClauses = whereClauses;
                        dlgDataExportConstruct.Geometry = tuFu.Geometry as IPolygon;
                        dlgDataExportConstruct.NeedCut = chkCut.Checked;
                        dlgDataExportConstruct.IsDelNullData = chkDelNullData.Checked;
                        dlgDataExportConstruct.SetProcessBarMax = setSubPgbMax;
                        dlgDataExportConstruct.SetProcessBarCurrent = setSubPgbCurrent;
                        dlgDataExportConstruct.NeedCut = chkCut.Checked;
                        dlgDataExportConstruct.WorkspaceType = workspaceType;
                        dlgDataExportConstruct.Path = txtExportPath.Text + "\\" + tuFu.Code;

                        dlgDataExportConstruct.CreateWsOnly = chkUseGP.Checked;

                        LogHelper.WriteLog("开始导出图幅[" + tuFu.Code + "]范围内的数据...\n");

                        doing = true;

                        if (!dlgDataExportConstruct.Operate())
                        {
                            if (breaked)
                            {
                                LogHelper.WriteLog("导出被终止。\n\n");
                                MsgHelper.ShowInfomationMsgbox("导出操作被终止！");
                                //breaked = false;
                            }
                            else
                            {
                                LogHelper.WriteErrLog("构造失败！！！\n\n");
                                //frmNewLog.IsSucceed = false;

                                MsgHelper.ShowWarningMsgbox("构造失败！详细信息请查看日志。");
                            }
                        }
                        else
                        {
                            List<DlgDataConvert> dlgDataConverts = dlgDataExportConstruct.DlgDataConverts;

                            dlgDataExport = new DlgDataExport();
                            dlgDataExport.Task = dlgDataConverts;
                            dlgDataExport.SetProcessBarMax = setAllPgbMax;
                            dlgDataExport.SetProcessBarCurrent = setAllPgbCurrent;                            
                            dlgDataExport.NeedRecord = chkAddResult.Checked;

                            if (dlgDataExport.Operate())
                            {
                                LogHelper.WriteLog("图幅[" + tuFu.Code + "]范围内的数据导出成功。\n\n");
                                //frmNewLog.IsSucceed = true;
                            }
                            else
                            {
                                if (breaked)
                                {
                                    LogHelper.WriteLog("导出被终止。\n\n");
                                    //MsgHelper.ShowInfomationMsgbox("导出操作被终止！");
                                    //breaked = false;
                                }
                                else
                                {
                                    LogHelper.WriteErrLog("图幅[" + tuFu.Code + "]范围内的数据导出操作失败！！！\n\n");
                                    //MsgHelper.ShowWarningMsgbox("图幅[" + tuFu.TuFuName + "]范围内的数据导出操作失败！详细信息请查看日志。");
                                    //frmNewLog.IsSucceed = false;
                                }
                            }

                            if (chkAddResult.Checked) pFeatClsesTarget.AddRange(dlgDataExport.FeatClsListTarget);
                        }
                        GC.Collect();
                    }
                    #endregion
                }
                else
                {
                    #region 导出到一个文件或者文件夹下
                    dlgDataExportConstruct = new DlgDataExportConstruct();
                    dlgDataExportConstruct.FeatClsListSource = pFeatClses;
                    dlgDataExportConstruct.TargetFeatClsNames = targetFeatCLsNames;
                    dlgDataExportConstruct.WhereClauses = whereClauses;
                    dlgDataExportConstruct.NeedCut = chkCut.Checked;
                    dlgDataExportConstruct.IsDelNullData = chkDelNullData.Checked;                    
                    dlgDataExportConstruct.SetProcessBarMax = setSubPgbMax;
                    dlgDataExportConstruct.SetProcessBarCurrent = setSubPgbCurrent;
                    dlgDataExportConstruct.WorkspaceType = workspaceType;
                    dlgDataExportConstruct.Path = txtExportPath.Text;

                    dlgDataExportConstruct.CreateWsOnly = chkUseGP.Checked;

                    if (!chkAll.Checked)
                    {
                        switch (tabControl2.SelectedTab.Text)
                        {
                            case "按图幅范围": //按图幅导出
                                var v = from o in chooseTuFu2.TuFus select o.Geometry;
                                dlgDataExportConstruct.Geometry = GeometryHelper.Union(v.ToList()) as IPolygon;
                                break;
                            case "按自定义范围": //按自定义范围
                                dlgDataExportConstruct.Geometry = pPolygonCustom;
                                break;

                            case "按测区范围":
                                dlgDataExportConstruct.Geometry = pPolygonSurvey;
                                break;

                            case "按行政区范围":
                                dlgDataExportConstruct.Geometry = pPolygonSurvey;
                                break;

                            default:
                                return;
                        }
                    }

                    doing = true;

                    if (!dlgDataExportConstruct.Operate())
                    {
                        if (breaked)
                        {
                            LogHelper.WriteLog("导出被终止。\n\n");
                            //MsgHelper.ShowInfomationMsgbox("导出操作被终止！");
                            breaked = false;
                        }
                        else
                        {
                            LogHelper.WriteErrLog("构造失败！！！\n\n");
                            //MsgHelper.ShowWarningMsgbox("构造失败！详细信息请查看日志。");
                            //frmNewLog.IsSucceed = false;
                        }
                    }
                    else
                    {
                        List<DlgDataConvert> dlgDataConverts = dlgDataExportConstruct.DlgDataConverts;

                        dlgDataExport = new DlgDataExport();
                        dlgDataExport.Task = dlgDataConverts;
                        dlgDataExport.SetProcessBarMax = setAllPgbMax;
                        dlgDataExport.SetProcessBarCurrent = setAllPgbCurrent;
                        
                        dlgDataExport.NeedRecord = chkAddResult.Checked;

                        if (dlgDataExport.Operate())
                        {
                            //LogHelper.WriteLog("导出成功。\n");
                            //frmNewLog.IsSucceed = true;
                        }
                        else
                        {
                            if (breaked)
                            {
                                LogHelper.WriteLog("导出被终止。\n\n");
                                //MsgHelper.ShowInfomationMsgbox("导出操作被终止！");
                                breaked = false;
                            }
                            else
                            {
                                LogHelper.WriteErrLog("导出失败！！！\n\n");
                                //frmNewLog.IsSucceed = false;
                                //MsgHelper.ShowWarningMsgbox("导出操作失败！详细信息请查看日志。");
                            }
                        }

                        if (chkAddResult.Checked) pFeatClsesTarget.AddRange(dlgDataExport.FeatClsListTarget);
                    }
                    #endregion
                }

                #region 加载导出结果
                if (chkAddResult.Checked)
                {
                    LogHelper.WriteLog("正在加载导出结果...");
                    foreach (IFeatureClass pFeatCLs in pFeatClsesTarget)
                    {
                        IFeatureLayer pFeatLyr = new FeatureLayerClass();
                        pFeatLyr.FeatureClass = pFeatCLs;
                        pFeatLyr.Name = pFeatCLs.AliasName + "_导出";
                        m_pMap.AddLayer(pFeatLyr);
                    }

                    LogHelper.WriteLog("加载完毕。");
                }
                #endregion

                //if (!chkLog.Checked) 
                MsgHelper.ShowInfomationMsgbox("导出完毕！");

                (m_Application as IFramework).DockManager.ActivateDockPanel("日志");
            }

            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("导出失败！" + ex.Message);
                LogHelper.WriteErrLog("导出失败！" + ex.Message);

                //frmNewLog.IsSucceed = false;
            }
            finally
            {
                #region 写数据提供日志
                /*
                //如果用户在中途就终止操作了，就不写日志
                if (chkLog.Checked && !breaked)
                {
                    IGeometry pGeometry = null;
                    if (!chkAll.Checked)
                    {
                        switch (tabControl2.SelectedTab.Text)
                        {
                            case "按图幅范围": //按图幅导出
                                pGeometry = TuFuUtility.GetSelectTuFuRegionByList(chooseTuFu2.TuFus);
                                break;
                            case "按自定义范围": //按自定义范围
                                pGeometry = pPolygonCustom;
                                break;

                            case "按测区范围":
                                pGeometry = pPolygonSurvey;
                                break;
                        }
                    }
                    frmNewLog.Shape = pGeometry;
                    frmNewLog.Operator = (m_Application as IFramework).User.Name;

                    List<FeatCls> featClses = new List<FeatCls>();
                    for (int i = 0; i < targetFeatCLsNames.Count; i++)
                    {
                        FeatCls featCls = new FeatCls();
                        featCls.ClsName = targetFeatCLsNames[i];
                        featCls.Filter = whereClauses[i];

                        featClses.Add(featCls);
                    }

                    frmNewLog.FeatClses = featClses;
                    frmNewLog.SourceWS = (pFeatClses[0] as IDataset).Workspace;
                    frmNewLog.TargetPath = txtExportPath.ControlText;

                    frmNewLog.ShowDialog();

                    #region 提取日志写到xls
                    try
                    {
                        string folder = txtExportPath.ControlText;
                        if (!chkEpByTufu.Checked)
                        {
                            folder = folder.Substring(0, folder.LastIndexOf('\\'));
                        }
                        string filename = folder + "\\提取日志.xls";

                        FileInfo fi = new FileInfo(filename);
                        if (fi.Exists)
                            fi.Delete();

                        DataOperateLog dataOperateLog = LogUtility.logContainer.dataOperateLogs[LogUtility.logContainer.dataOperateLogs.Count - 1];// frmNewLog.DataOperateLog;

                        ComObject pExcel = ComObject.CreateComInstance("Excel.Application");
                        ComObject workBooks = ComObject.CreateInstance(pExcel["Workbooks"]);
                        ComObject pWorkbook = ComObject.CreateInstance(workBooks.InvokeMethod("Add"));

                        ComObject pWorksheet = ComObject.CreateInstance(pWorkbook["Worksheets", 1]);
                        pExcel["Visible"] = false;

                        ComObject pRange;

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 1]);
                        pRange["Value2"] = "操作员";
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 2, 1]);
                        pRange["Value2"] = dataOperateLog.Operator;

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 2]);
                        pRange["Value2"] = "数据源";
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 2, 2]);
                        pRange["Value2"] = dataOperateLog.SourcePath;

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 3]);
                        pRange["Value2"] = "数据";
                        int j = 2;
                        foreach (FeatCls featCls in dataOperateLog.FeatClses)
                        {
                            pRange = ComObject.CreateInstance(pWorksheet["Cells", j++, 3]);
                            pRange["Value2"] = featCls.ClsName;
                        }

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 4]);
                        pRange["Value2"] = "操作范围";
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 2, 4]);
                        pRange["Value2"] = dataOperateLog.Shape == "" ? "全图范围" : dataOperateLog.Shape;

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 5]);
                        pRange["Value2"] = "目标路径";
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 2, 5]);
                        pRange["Value2"] = dataOperateLog.TargetPath;

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 6]);
                        pRange["Value2"] = "操作时间";
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 2, 6]);
                        pRange["Value2"] = dataOperateLog.Time;

                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 1, 7]);
                        pRange["Value2"] = "备注";
                        pRange = ComObject.CreateInstance(pWorksheet["Cells", 2, 7]);
                        pRange["Value2"] = dataOperateLog.Remark;

                        SaveAs(filename, pWorkbook);
                        pExcel.InvokeMethod("Quit");

                    }
                    catch (Exception ex)
                    {
                        MsgHelper.ShowWarningMsgbox("保持提取日志失败：" + ex.Message);
                    }
                    #endregion

                }

                */
                #endregion

                #region 扫尾工作
                dlgDataExportConstruct = null;
                dlgDataExport = null;
                progressBarSub.Visible = false;
                progressBarAll.Visible = false;
                //btnCancel.Visible = false;
                doing = false;
                breaked = false;
                pFeatClses = null;
                targetFeatCLsNames = null;
                whereClauses = null;
                #endregion
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            switch (cboType.SelectedIndex)
            {
                case 0://gdb
                case 1://mdb  
                case 3://dwg
                    {

                        if (chkEpByTufu.Checked)
                        {
                            FolderBrowserDialog fbdlg = new FolderBrowserDialog();
                            fbdlg.ShowNewFolderButton = true;
                            fbdlg.Description = "选择导出路径";
                            if (fbdlg.ShowDialog() == DialogResult.OK)
                            {
                                txtExportPath.Text = fbdlg.SelectedPath;
                            }
                        }
                        else
                        {
                            saveFileExport.Title = "指定目标文件";
                            if (cboType.SelectedIndex == 0)
                            {
                                saveFileExport.Filter = "File Geodatabase (*.gdb)| *.gdb";
                                if (saveFileExport.ShowDialog() == DialogResult.OK)
                                {
                                    txtExportPath.Text = saveFileExport.FileName.Substring(0, saveFileExport.FileName.Length - 4);
                                }
                            }
                            else if (cboType.SelectedIndex == 1)
                            {
                                saveFileExport.Filter = "Personal Geodatabase(*.mdb) | *.mdb";
                                if (saveFileExport.ShowDialog() == DialogResult.OK)
                                {
                                    txtExportPath.Text = saveFileExport.FileName.Substring(0, saveFileExport.FileName.Length - 4);
                                }
                            }
                            else if (cboType.SelectedIndex == 3)
                            {
                                saveFileExport.Filter = "AutoCAD dwg 文件(*.dwg) | *.dwg";
                                if (saveFileExport.ShowDialog() == DialogResult.OK)
                                {
                                    txtExportPath.Text = saveFileExport.FileName;
                                }
                            }
                        }
                        break;
                    }
                case 2://shp
                //case 3://e00
                //case 5://mif
                    {
                        FolderBrowserDialog fbdlg = new FolderBrowserDialog();
                        fbdlg.ShowNewFolderButton = true;
                        fbdlg.Description = "选择导出路径";
                        if (fbdlg.ShowDialog() == DialogResult.OK)
                        {
                            txtExportPath.Text = fbdlg.SelectedPath;
                            //m_pExportType = cboType.SelectedIndex;
                        }
                        break;
                    }
                //case 4:
                //    {
                //        if (chkEpByTufu.Checked)
                //        {
                //            FolderBrowserDialog fbdlg = new FolderBrowserDialog();
                //            fbdlg.ShowNewFolderButton = true;
                //            fbdlg.Description = "选择导出路径";
                //            if (fbdlg.ShowDialog() == DialogResult.OK)
                //            {
                //                txtExportPath.ControlText = fbdlg.SelectedPath;
                //                //m_pExportType = cboType.SelectedIndex;
                //            }
                //        }
                //        else
                //        {
                //            saveFileExport.Filter = "AutoCAD dwg 文件(*.dwg) | *.dwg";
                //            if (saveFileExport.ShowDialog() == DialogResult.OK)
                //            {
                //                txtExportPath.ControlText = saveFileExport.FileName;
                //            }
                //        }
                //        break;
                //    }
              

                default:
                    {
                        break;
                    }

            }
            txtExportPath.Tooltip = txtExportPath.Text;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdCancel_Click(object sender, EventArgs e)
        {
            if (doing)// && dlgDataImportByCode != null)
            {
                if (MsgHelper.ShowYesOrNoQueryMsgBox("是否要终止导出操作？") == DialogResult.Yes)
                {
                    //if (dlgDataExportConstruct != null) dlgDataExportConstruct.Stop();
                    if (dlgDataExport != null) dlgDataExport.Stop();
                    breaked = true;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboType_Click(object sender, EventArgs e)
        {
            txtExportPath.Text = "";
            txtExportPath.Tooltip = txtExportPath.Text;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveRule_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewByMap.RowCount == 0) return;

                #region 判断是否有选中图层
                List<DataGridViewRow> dgrRows = new List<DataGridViewRow>();
                for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                    {
                        dgrRows.Add(dataGridViewByMap.Rows[i]);
                    }
                }

                if (dgrRows.Count == 0)
                {
                    MsgHelper.ShowInfomationMsgbox("没有图层被选中，无需保存。");
                    return;
                }
                #endregion

                #region 设置新方案名称，或者选择已有方案
                FrmSaveRule frmSaveRule = new FrmSaveRule(zjgisRuleType.dlgExp);
                frmSaveRule.RuleName = ruleName;

                if (frmSaveRule.ShowDialog() == DialogResult.Cancel) return;

                object obj = frmSaveRule.Rule;
                DataExportRule dataExportRule;

                bool isNewRule = false;

                if (obj is string)
                {
                    dataExportRule = new DataExportRule();
                    dataExportRule.RuleName = obj.ToString();
                    isNewRule = true;
                }
                else if (obj is DataExportRule)
                {
                    dataExportRule = obj as DataExportRule;
                }
                else
                {
                    MsgHelper.ShowWarningMsgbox("选择方案名称无效，无法保存！");
                    return;
                }
                #endregion

                #region 是否裁切、导出类型
                dataExportRule.Cutable = chkCut.Checked;
                dataExportRule.IsDelNullData = chkDelNullData.Checked;
                dataExportRule.ExportType = cboType.SelectedItem.ToString();
                #endregion

                #region 导出图层
                List<DataExportLayer> dataExportLayers = new List<DataExportLayer>();
                foreach (DataGridViewRow dgvRow in dgrRows)
                {
                    DataExportLayer dataExportLayer = new DataExportLayer();

                    IFeatureLayer pFeatureLayer = dgvRow.Tag as IFeatureLayer;

                    dataExportLayer.FeatLyrName = pFeatureLayer.Name;
                    dataExportLayer.SourceFeatClsName = (pFeatureLayer.FeatureClass as IDataset).Name;

                    string targetFeatClsName = StringHelper.ConvertWRTNull(dgvRow.Cells[2].Value);
                    if (targetFeatClsName == "") targetFeatClsName = (pFeatureLayer.FeatureClass as IDataset).Name;
                    dataExportLayer.TargetFeatClsName =targetFeatClsName ;

                    dataExportLayer.SQL = StringHelper.ConvertWRTNull(dgvRow.Cells[3].Value);
                    dataExportLayers.Add(dataExportLayer);
                }
                dataExportRule.DataExportLayers = dataExportLayers;
                #endregion

                #region 设置空间范围
                SpatialSetting spatialSetting = new SpatialSetting();

                if (chkAll.Checked)
                {
                    spatialSetting.SpatialType = 0;
                }
                else
                {
                    switch (tabControl2.SelectedTab.Text)
                    {
                        case "按图幅范围":
                            spatialSetting.SpatialType = 1;

                            MapsheetInfo mapsheetInfo = new MapsheetInfo();
                            mapsheetInfo.Splitable = chkEpByTufu.Checked;
                            mapsheetInfo.Scale = chooseTuFu2.ScaleValue.ToString();

                            List<Mapsheet> tufus = chooseTuFu2.TuFus;
                            string mapNo = "";
                            foreach (Mapsheet tufu in tufus)
                            {
                                mapNo = mapNo + tufu.Code + ";";
                            }

                            if (mapNo != "") mapNo = mapNo.Substring(0, mapNo.Length - 1);
                            mapsheetInfo.MapNo = mapNo;

                            spatialSetting.MapsheetInfo = mapsheetInfo;

                            break;

                        case "按测区范围":
                            spatialSetting.SpatialType = 2;

                            CequInfo cequInfo = new CequInfo();

                            IGeometry pGeometry = chooseFWX2.PolygonFWX;

                            if (pGeometry != null && pGeometry.IsEmpty == false)
                            {

                                IXMLWriter pWriter = new XMLWriterClass();
                                IXMLStream pStream = new XMLStreamClass();

                                pWriter.WriteTo(pStream as IStream);

                                IXMLSerializer pSerializer = new XMLSerializerClass();
                                pSerializer.WriteObject(pWriter, null, null, "Shape", "", pGeometry);
                                string shape = pStream.SaveToString();

                                cequInfo.Geometry = shape;
                            }

                            spatialSetting.CequInfo = cequInfo;

                            break;

                        case "按行政区范围":
                            spatialSetting.SpatialType = 3;

                            XzqInfo xzqInfo = new XzqInfo();

                            List<Xzq> xzqqs = new List<Xzq>();
                            List<XZQ> xzqs = selectXZQ1.XzqChecked;

                            foreach (XZQ xzq in xzqs)
                            {
                                Xzq xzqq = new Xzq();
                                xzqq.Code = xzq.XZQCode;
                                xzqq.Name = xzq.XZQName;

                                xzqqs.Add(xzqq);
                            }

                            xzqInfo.Xzqs = xzqqs;

                            spatialSetting.XzqInfo = xzqInfo;

                            break;
                        default:
                            MsgHelper.ShowWarningMsgbox("空间范围设置异常！");
                            return;
                    }
                }

                dataExportRule.SpatialSetting = spatialSetting;
                #endregion

                #region 保存方案
                if (isNewRule)
                {
                    List<DataExportRule> dataExportRules = ConvertHelper.DataConvert.DataExportRules;
                    dataExportRules.Add(dataExportRule);
                }
                ConfigHelper.SaveObject<DataConvert>(ConvertHelper.DataConvert, "Rule");
                #endregion

                ruleName = dataExportRule.RuleName;

                MsgHelper.ShowInfomationMsgbox("保存成功。");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("保存失败：" + ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenRule_Click(object sender, EventArgs e)
        {
            try
            {
                FrmSelRule frmSelectRule = new FrmSelRule(zjgisRuleType.dlgExp);

                frmSelectRule.TypeComboxVisable = true;
                if (frmSelectRule.ShowDialog() != DialogResult.OK) return;

                DataExportRule dataExportRule = frmSelectRule.Rule as DataExportRule;
                if (dataExportRule == null) return;

                Cursor = Cursors.WaitCursor;

                ruleName = dataExportRule.RuleName;

                #region 图层信息
                List<DataExportLayer> dataExportLayers = dataExportRule.DataExportLayers;
                foreach (DataGridViewRow dgvR in this.dataGridViewByMap.Rows)
                {
                    if (dgvR.Tag == null || !(dgvR.Tag is IFeatureLayer)) continue;

                    IFeatureLayer pFeatLyr = dgvR.Tag as IFeatureLayer;
                    List<DataExportLayer> dels;
                    DataExportLayer dataExportLayer = null;
                    string lyrName = pFeatLyr.Name;
                    string dsName = (pFeatLyr.FeatureClass as IDataset).Name;

                    switch (frmSelectRule.MatchType)
                    {
                        case 0:

                            dels = ListHelper.GetEnumeratorItems(dataExportLayers, "FeatLyrName", lyrName);

                            if (dels.Count == 1)
                            {
                                dataExportLayer = dels[0];
                            }
                            else if (dels.Count > 1)
                            {
                                dataExportLayer = ListHelper.GetEnumeratorItem(dels, "SourceFeatClsName", dsName);
                                if (dataExportLayer == null) dataExportLayer = dels[0];
                            }

                            break;

                        case 1:

                            dels = ListHelper.GetEnumeratorItems(dataExportLayers, "SourceFeatClsName", dsName);

                            if (dels.Count == 1)
                            {
                                dataExportLayer = dels[0];
                            }
                            else if (dels.Count > 1)
                            {
                                dataExportLayer = ListHelper.GetEnumeratorItem(dels, "FeatLyrName", lyrName);
                                if (dataExportLayer == null) dataExportLayer = dels[0];
                            }

                            break;
                    }

                    if (dataExportLayer != null)
                    {
                        dgvR.Cells[0].Value = true;
                        dgvR.Cells[2].Value = StringHelper.ConvertWRTNull(dataExportLayer.TargetFeatClsName);
                        dgvR.Cells[3].Value = StringHelper.ConvertWRTNull(dataExportLayer.SQL);
                    }
                    else
                    {
                        dgvR.Cells[0].Value = false;
                    }
                }
                #endregion

                #region 裁切、导出类型
                chkCut.Checked = dataExportRule.Cutable;
                chkDelNullData.Checked = dataExportRule.IsDelNullData;
                cboType.Text = dataExportRule.ExportType.ToLower();
                #endregion

                #region 空间范围信息
                SpatialSetting spatialSetting = dataExportRule.SpatialSetting;
                chkAll.Checked = false;
                switch (spatialSetting.SpatialType)
                {
                    case 0:
                        chkAll.Checked = true;
                        break;

                    case 1:
                        tabControl2.SelectedTabIndex = 0;
                        MapsheetInfo mapsheetInfo = spatialSetting.MapsheetInfo;
                        if (mapsheetInfo == null) break;

                        int scale = int.Parse(mapsheetInfo.Scale);
                        chooseTuFu2.SetScale(scale);
                        chkEpByTufu.Checked = mapsheetInfo.Splitable;

                        string[] tufuStrs = mapsheetInfo.MapNo.Split(';');
                        List<string> tufuList = new List<string>(tufuStrs);

                        List<Mapsheet> tufus = new List<Mapsheet>();
                        foreach (string tufuStr in tufuList)
                        {
                            Mapsheet tufu = new Mapsheet();
                            tufu.Code = tufuStr;
                            tufus.Add(tufu);
                        }
                        chooseTuFu2.SetTufus(tufus);

                        break;

                    case 2:
                        tabControl2.SelectedTabIndex = 1;
                        CequInfo cequInfo = spatialSetting.CequInfo;
                        if (cequInfo == null) break;

                        try
                        {
                            IXMLReader pReader = new XMLReaderClass();
                            IXMLStream pStream = new XMLStreamClass();

                            string xml = cequInfo.Geometry;
                            xml = xml.Replace("&lt;", "<");
                            xml = xml.Replace("&gt;", ">");
                            pStream.LoadFromString(xml);
                            pReader.ReadFrom(pStream as IStream);

                            IXMLSerializer pSerializer = new XMLSerializerClass();

                            IGeometry pGeometry = pSerializer.ReadObject(pReader, null, null) as IGeometry;
                            if (pGeometry == null || pGeometry.IsEmpty) break;

                            (m_pMap as IActiveView).Extent = pGeometry.Envelope;
                            (m_pMap as IActiveView).Refresh();

                            chooseFWX2.AfterButtonOkEvent(pGeometry, 0);
                            AfterButtonOkEvent(pGeometry, 0);

                        }
                        catch (Exception ex)
                        {
                            MsgHelper.ShowWarningMsgbox("反序列化测区图形失败：" + ex.Message);
                        }

                        break;

                    case 3:
                        tabControl2.SelectedTabIndex = 3;
                        XzqInfo xzqInfo = spatialSetting.XzqInfo;
                        if (xzqInfo == null) break;

                        List<XZQ> xzqs = new List<XZQ>();

                        foreach (Xzq xxzzqq in xzqInfo.Xzqs)
                        {
                            XZQ xzq = new XZQ();
                            xzq.XZQCode = xxzzqq.Code;
                            xzq.XZQName = xxzzqq.Name;
                            xzqs.Add(xzq);
                        }

                        selectXZQ1.XzqChecked = xzqs;

                        break;
                }
                #endregion

                MsgHelper.ShowInfomationMsgbox("加载方案成功。");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("加载方案失败：" + ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewByMap_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (this.dataGridViewByMap.RowCount == 0) return;
            if (e.ColumnIndex != 3) return;

            DataGridViewRow dgvR = this.dataGridViewByMap.Rows[e.RowIndex];

            if (dgvR.Tag != null && dgvR.Tag is IFeatureLayer)
            {
                FrmQueryByAttribute frmSQL = new FrmQueryByAttribute();

                frmSQL.Application = m_Application;
                frmSQL.FeatureLayerExp = (dgvR.Tag as IFeatureLayer);
                frmSQL.WhereCause = (dataGridViewByMap.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                frmSQL.CmdOKClick = delegate(string sSQL)
                {
                    dataGridViewByMap.Rows[e.RowIndex].Cells[3].Value = sSQL;
                    dataGridViewByMap.RefreshEdit();
                };
                frmSQL.ShowDialog(this);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewByMap_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            //第一列复选框的值发生变化时，联动改变树节点的勾选情况
            if (e.ColumnIndex == 0)
            {
                //增加这句话，预防初始化时出错
                if ((dataGridViewByMap.Rows.Count == 0) || (e.RowIndex < 0)) return;

                if (dataGridViewByMap.Rows[e.RowIndex].Tag == null || !(dataGridViewByMap.Rows[e.RowIndex].Tag is IFeatureLayer)) return;

                IFeatureLayer pFeatLyr = dataGridViewByMap.Rows[e.RowIndex].Tag as IFeatureLayer;

                List<TreeNode> treeNodes = TreeHelper.GetAllYzTreeNode2(treeView1.Nodes[0]);

                foreach (TreeNode treeNode in treeNodes)
                {
                    if (treeNode.Tag == null || !(treeNode.Tag is IFeatureLayer)) continue;

                    IFeatureLayer pFeatLyr2 = treeNode.Tag as IFeatureLayer;
                    if (pFeatLyr.Equals(pFeatLyr2))
                    {
                        grid = true;

                        treeNode.Checked = (bool)dataGridViewByMap.Rows[e.RowIndex].Cells[0].Value;

                        TreeHelper.CheckChildrenBySelf(treeNode, treeNode.Checked);
                        TreeHelper.SetParentNodeState(treeNode);

                        grid = false;

                        return;
                    }
                }

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewByMap_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContextMenuStrip pContextMenu = new ContextMenuStrip();
                ToolStripMenuItem pItemSelectAll = new ToolStripMenuItem("全选");
                pItemSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemSelectAll);
                ToolStripMenuItem pItemUnSelectAll = new ToolStripMenuItem("全不选");
                pItemUnSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemUnSelectAll);

                ToolStripMenuItem pItemCheckSelectAll = new ToolStripMenuItem("选中项勾选");
                pItemUnSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemCheckSelectAll);

                ToolStripMenuItem pItemUnCheckSelectAll = new ToolStripMenuItem("选中项不勾选");
                pItemUnSelectAll.Enabled = dataGridViewByMap.Rows.Count > 0;
                pContextMenu.Items.Add(pItemUnCheckSelectAll);

                pItemSelectAll.Click += new EventHandler(pItemSelectAll_Click);
                pItemUnSelectAll.Click += new EventHandler(pItemUnSelectAll_Click);
                pItemCheckSelectAll.Click += new EventHandler(pItemCheckSelectAll_Click);
                pItemUnCheckSelectAll.Click += new EventHandler(pItemUnCheckSelectAll_Click);

                pContextMenu.Show(this.dataGridViewByMap, e.X, e.Y);

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSplit_CheckedChanged(object sender, CheckBoxChangeEventArgs e)
        {
            chkCut.Checked = true;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkAll_CheckedChanged(object sender, CheckBoxChangeEventArgs e)
        {
            chkCut.Enabled = !chkAll.Checked;
            chkEpByTufu.Enabled = !chkAll.Checked;
            chooseFWX2.Enabled = !chkAll.Checked;
            chooseTuFu2.Enabled = !chkAll.Checked;
            selectAreaControl2.Enabled = !chkAll.Checked;
            selectXZQ1.Enabled = !chkAll.Checked;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl2_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e)
        {
            if (chkAll.Checked) return;
            if (this.tabControl2.SelectedTabIndex != 0)
            {
                chkEpByTufu.Enabled = false;
            }
            else
            {
                chkEpByTufu.Enabled = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag != null && (e.Node.Tag is IFeatureLayer))
            {

                IFeatureLayer pFeatLyr = e.Node.Tag as IFeatureLayer;

                foreach (DataGridViewRow dgvr in dataGridViewByMap.Rows)
                {
                    if (dgvr.Tag == null || !(dgvr.Tag is IFeatureLayer)) continue;

                    IFeatureLayer pFeatLyr2 = dgvr.Tag as IFeatureLayer;

                    if (pFeatLyr.Equals(pFeatLyr2))
                    {
                        tree = true;
                        dgvr.Cells[0].Value = e.Node.Checked;
                        tree = false;
                        return;
                    }
                }
            }


            if (!tree && !grid)
            {
                tree = true;
                TreeHelper.SetParentNodeState(e.Node);
                TreeHelper.CheckChildrenBySelf(e.Node, e.Node.Checked);
            }
            else
            {
                return;
            }

            tree = false;
        }

        #region 进度条事件
        /// <summary>
        /// 
        /// </summary>
        /// <param name="max"></param>
        private void setSubPgbMax(int max)
        {
            progressBarSub.Maximum = max;
            progressBarSub.Minimum = 0;
            progressBarSub.Value = 0;
            Application.DoEvents();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        private void setSubPgbCurrent(int current)
        {
            if (current <= progressBarSub.Maximum)
            {
                progressBarSub.Value = (int)current;

                double dRate = current * 100.0 / progressBarSub.Maximum;
                int iRate = (int)Math.Floor(dRate);
                progressBarSub.TextVisible = true;
                progressBarSub.Text = "分进度：" + current.ToString() + "/" + progressBarSub.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                //dataGridViewX1.UseWaitCursor = true;
            }
            else
            {
                progressBarSub.Value = (int)progressBarSub.Maximum;
                progressBarSub.TextVisible = false;
                //dataGridViewX1.UseWaitCursor = false;
            }
            progressBarSub.Update();
            if (progressBarSub.Maximum < 200)
                Application.DoEvents();
            else
                if (current % (progressBarSub.Maximum / 100) == 0) Application.DoEvents();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="max"></param>
        private void setAllPgbMax(int max)
        {
            progressBarAll.Maximum = max;
            progressBarAll.Minimum = 0;
            progressBarAll.Value = 0;
            Application.DoEvents();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        private void setAllPgbCurrent(int current)
        {
            if (current <= progressBarAll.Maximum)
            {
                progressBarAll.Value = (int)current;

                double dRate = current * 100.0 / progressBarAll.Maximum;
                int iRate = (int)Math.Floor(dRate);
                progressBarAll.TextVisible = true;
                progressBarAll.Text = "总进度：" + current.ToString() + "/" + progressBarAll.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                //dataGridViewX1.UseWaitCursor = true;
            }
            else
            {
                progressBarAll.Value = (int)progressBarAll.Maximum;
                progressBarAll.TextVisible = false;
                //dataGridViewX1.UseWaitCursor = false;
            }
            progressBarAll.Update();
            if (progressBarAll.Maximum < 200)
                Application.DoEvents();
            else
                if (current % (progressBarAll.Maximum / 100) == 0) Application.DoEvents();
        }
        #endregion

        #region 右键菜单
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemUnSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
            {
                dataGridViewByMap.Rows[i].Cells[0].Value = false;
            }

            dataGridViewByMap.RefreshEdit();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
            {
                dataGridViewByMap.Rows[i].Cells[0].Value = true;
            }

            dataGridViewByMap.RefreshEdit();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemCheckSelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow pRow in dataGridViewByMap.SelectedRows)
            {
                pRow.Cells[0].Value = true;
            }

            dataGridViewByMap.RefreshEdit();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pItemUnCheckSelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow pRow in dataGridViewByMap.SelectedRows)
            {
                pRow.Cells[0].Value = false;
            }

            dataGridViewByMap.RefreshEdit();
        }
        #endregion

        #endregion

        /// <summary>
        /// 自定义范围控件画完之后调用的事件
        /// </summary>
        /// <param name="pGeom"></param>
        /// <param name="shift"></param>
        private void AfterButtonOkEvent(IGeometry pGeom, int shift)
        {
            if (pGeom == null || pGeom.IsEmpty || pGeom is IPoint)
            {
                return;
            }
            try
            {
                if (pGeom is IEnvelope)
                {
                    pGeom = ((IEnvelope)pGeom).ToPolygon();
                }
                else if (pGeom is ICircularArc)
                {
                    IPolygon pPolygon = new PolygonClass();
                    ISegmentCollection pSegCollection = pPolygon as ISegmentCollection;
                    object missing = System.Type.Missing;
                    pSegCollection.AddSegment(pGeom as ISegment, ref missing, ref missing);
                    pPolygon.SpatialReference = pGeom.SpatialReference;
                    pGeom = pPolygon;
                }

                if (pGeom == null || pGeom.IsEmpty) return;

                Cursor = Cursors.Default;

                pPolygonCustom = pGeom as IPolygon;
                GeometryUserDraw(pPolygonCustom);
            }
            catch (System.Exception)
            {

            }
            finally
            {
                this.WindowState = FormWindowState.Normal;
            }

        }

        /// <summary>
        /// 画用户权限内的范围
        /// </summary>
        /// <param name="pPolyUserDraw"></param>
        private void GeometryUserDraw(IPolygon pPolyUserDraw)
        {
            if (pPolyUserDraw == null || pPolyUserDraw.IsEmpty) return; ;
            IPolyline pPolyline = pPolyUserDraw.ToPolyline();

            IRgbColor pRgbColor = new RgbColorClass();
            pRgbColor.Red = 255;
            pRgbColor.Green = 155;
            pRgbColor.Blue = 0;

            IActiveView pActiveView = (m_Application.Document as IMxDocument).ActiveView;
            IGraphicsContainer pGeoContainer = pActiveView as IGraphicsContainer;
            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            ISimpleLineSymbol pLineSymbol = new SimpleLineSymbolClass();
            ILineElement pLineElement = new LineElementClass();
            pLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
            pLineSymbol.Color = pRgbColor;
            pLineSymbol.Width = 3;
            pLineElement.Symbol = pLineSymbol;
            m_pElementUserDraw = pLineElement as IElement;
            m_pElementUserDraw.Geometry = pPolyline;
            pGeoContainer.AddElement(m_pElementUserDraw, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pActiveView.Extent);
        }

        /// <summary>
        /// 初始化图层列表和图层树
        /// </summary>
        private void RefreshCurMapLayer()
        {
            
            //当前地图的图层
            if (m_Application != null && (m_Application.Document as IMxDocument).ActiveView.FocusMap != null)
            {

                m_pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;

            }
            else
                return;

            dataGridViewByMap.Rows.Clear();
            dataGridViewByMap.Columns[1].ReadOnly = true;

            #region 界面上仅显示图层名，没有组的信息
            //读取所有图层
            //if (m_pMap != null)
            //{
            //    List<IFeatureLayer> pFeaturelyrs = MapHelper.GetAllLayer<IFeatureLayer>(m_pMap);
            //    IFeatureLayer pFeaturelayer;
            //    string strFclsName = "";
            //    for (int i = 0; i < pFeaturelyrs.Count; i++)
            //    {
            //        pFeaturelayer = pFeaturelyrs[i];
            //        if (!(pFeaturelayer.Valid) || !(pFeaturelayer.Visible)) continue;
            //        if (pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTSimple || 
            //            pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation )
            //        {
            //            strFclsName = ((IDataset)pFeaturelayer.FeatureClass).Name;
            //            if (strFclsName.IndexOf(".") > 0)
            //            {
            //                strFclsName = strFclsName.Substring(strFclsName.IndexOf(".") + 1);
            //            }
            //            dataGridViewByMap.Rows.Add(1);
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[0].Value = true;
            //            //数据源显示图层(FeatureLayer)的名称，与TOC对应
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[1].Value = pFeaturelayer.Name;// strFclsName;

            //            //dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[1].Tag =
            //            //    pFeaturelayer.FeatureClass;
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[2].Value = strFclsName;

            //            //属性过滤条件默认显示该图层的DefinitionExpression
            //            IFeatureLayerDefinition pFeatureLayerDefinition = pFeaturelayer as IFeatureLayerDefinition;
            //            string definitionExpression = pFeatureLayerDefinition.DefinitionExpression;
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[3].Value = definitionExpression;

            //            //dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer.FeatureClass;
            //            dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer;

            //        }
            //    }
            //}
            #endregion

            //读取所有图层
            if (m_pMap != null)
            {
                //TreeView treeView = new TreeView();
                TreeNode root = TocHelper.ConstructLyrTree(m_pMap);
                //treeView.Nodes.Add(root);

                root.Text = "所有图层";
                root.Checked = true;
                root.Expand();
                TreeHelper.CheckChildrenBySelf(root, root.Checked);
                treeView1.Nodes.Add(root);

                List<TreeNode> treeNodes = TreeHelper.GetAllYzTreeNode2(root);

                foreach (TreeNode treeNode in treeNodes)
                {
                    if (treeNode.Tag == null || !(treeNode.Tag is IFeatureLayer)) continue;
                    IFeatureLayer pFeaturelayer;
                    string strFclsName = "";
                    pFeaturelayer = treeNode.Tag as IFeatureLayer;
                    if (!pFeaturelayer.Valid) continue;
                    if (pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTSimple ||
                        pFeaturelayer.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                    {
                        strFclsName = ((IDataset)pFeaturelayer.FeatureClass).Name;
                        if (strFclsName.IndexOf(".") > 0)
                        {
                            strFclsName = strFclsName.Substring(strFclsName.IndexOf(".") + 1);
                        }
                        dataGridViewByMap.Rows.Add(1);
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[0].Value = true;

                        //数据源显示图层(FeatureLayer)的名称，与TOC对应(附上组信息)
                        string fullPath = treeNode.FullPath;
                        fullPath = fullPath.Substring(fullPath.IndexOf("\\") + 1);
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[1].Value = fullPath;

                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[2].Value = strFclsName;

                        //属性过滤条件默认显示该图层的DefinitionExpression
                        IFeatureLayerDefinition pFeatureLayerDefinition = pFeaturelayer as IFeatureLayerDefinition;
                        string definitionExpression = pFeatureLayerDefinition.DefinitionExpression;
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Cells[3].Value = definitionExpression;

                        //dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer.FeatureClass;
                        dataGridViewByMap.Rows[dataGridViewByMap.Rows.Count - 1].Tag = pFeaturelayer;
                    }

                }
            }
        }

        /// <summary>
        /// 判断是否有图层选中
        /// </summary>
        /// <returns></returns>
        private bool AnyLayerChecked()
        {
            if (dataGridViewByMap.RowCount == 0) return false;
            for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 保存数据操作日志到Excel
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="workBook"></param>
        private static void SaveAs(string FileName, ComObject workBook)
        {
            int pXlFileFormat = -4143;
            string kong1 = "";
            string kong2 = "";
            bool False1 = false;
            bool False2 = false;
            int pXlSaveAsAccessMode = 1;
            int pXlSaveConflictResolution = 2;
            bool False3 = false;
            object null1 = null;
            object null2 = null;
            bool False4 = false;

            object[] objArr = new object[12];
            objArr[0] = FileName;
            objArr[1] = pXlFileFormat;
            objArr[2] = kong1;
            objArr[3] = kong2;
            objArr[4] = False1;
            objArr[5] = False2;
            objArr[6] = pXlSaveAsAccessMode;
            objArr[7] = pXlSaveConflictResolution;
            objArr[8] = False3;
            objArr[9] = null1;
            objArr[10] = null2;
            objArr[11] = False4;

            workBook.InvokeMethod("SaveAs", objArr);
        }

        /// <summary>
        /// 获取所有选中图层
        /// </summary>
        /// <returns></returns>
        private List<IFeatureLayer> GetCheckLayers()
        {
            List<IFeatureLayer> pLayers = new List<IFeatureLayer>();
            for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                {
                    pLayers.Add(dataGridViewByMap.Rows[i].Tag as IFeatureLayer);
                }
            }
            return pLayers;
        }
        
        #region 导出其它格式数据
        
        private void ExportE00()
        {
            try
            {
                progressBarSub.Visible = true;
                progressBarAll.Visible = true;
                
                this.Cursor = Cursors.WaitCursor;
                IGeometry pGeometry = null;
                IFeatureLayer pFeatureLayer = null;
                string strFilter, strTargetFileName;
                if (tabControl2.SelectedTab.Text == "按图幅范围")
                {
                    if (!chkEpByTufu.Checked && chooseTuFu2.TuFus.Count > 0)
                    {
                        var v = from o in chooseTuFu2.TuFus select o.Geometry;
                        pGeometry = GeometryHelper.Union(v.ToList()) as IPolygon;

                    }
                }
                else if (tabControl2.SelectedTab.Text == "按自定义范围")
                {
                    pGeometry = pPolygonCustom;
                }
                else if (tabControl2.SelectedTab.Text == "按测区范围")
                {
                    pGeometry = chooseFWX2.PolygonFWX;
                }
                else if (tabControl2.SelectedTab.Text == "按行政区范围")
                {
                    pGeometry = selectXZQ1.GetGeometry();
                }
                E00DwgExport pE00Ep = new E00DwgExport();
                pE00Ep.Path = txtExportPath.Text;
                pE00Ep.Clip = chkCut.Checked;
                pE00Ep.TempFeatureWorkspace = CreateGdbWks(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "E00Temp.gdb");
                for (int i = 0; i < dataGridViewByMap.Rows.Count; i++)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer )
                    {
                        pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
                        IFeatureClass pFeatCls;
                        pFeatCls = pFeatureLayer.FeatureClass;

                        if (pFeatCls.FeatureType == esriFeatureType.esriFTAnnotation)
                        {
                            //if (!hasWarnAnnoException)
                            //{
                            //    MsgHelper.ShowInfomationMsgbox("本系统暂不支持将注记层导出为E00格式！");
                            //    hasWarnAnnoException = true;
                            //}
                            //continue;
                            LogHelper.WriteLog("暂不支持将注记层导出为E00格式,图层"+pFeatureLayer.Name +"将不被导出");
                            continue;
                        }
                        LogHelper.WriteLog("正在导出图层'" + pFeatureLayer.Name+"'" );        
                        pE00Ep.FeatureLayer = pFeatureLayer;
                        strTargetFileName = dataGridViewByMap.Rows[i].Cells[2].Value == null ? pFeatureLayer.Name : dataGridViewByMap.Rows[i].Cells[2].Value.ToString();
                        strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
                        if (tabControl2.SelectedTab.Text == "按图幅范围" && chkEpByTufu.Checked && chooseTuFu2.TuFus.Count > 0)
                        {
                            DirectoryInfo dir = new DirectoryInfo(txtExportPath.Text);
                            for (int j = 0; j < chooseTuFu2.TuFus.Count; j++)
                            {
                                dir.CreateSubdirectory(chooseTuFu2.TuFus[j].Code);
                                pE00Ep.Path = txtExportPath.Text + "\\" + chooseTuFu2.TuFus[j].Code;
                                pE00Ep.FilterGeometry = chooseTuFu2.TuFus[j].Geometry;
                                pE00Ep.Filter = strFilter;
                                pE00Ep.TargetFileName = strTargetFileName;
                               
                                    pE00Ep.ExportE00();
                                
                            }
                        }
                        else
                        {
                            pE00Ep.FilterGeometry = pGeometry;
                            pE00Ep.Filter = strFilter;
                            pE00Ep.TargetFileName = strTargetFileName;
                           
                                pE00Ep.ExportE00();
                            
                        }
                    }
                }
                LogHelper.WriteLog("导出完毕");
                MsgHelper.ShowInfomationMsgbox("导出完毕！");
            }
            catch (System.Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("导出失败：" + ex.Message);
            }
            finally
            {
                progressBarSub.Visible = false ;
                progressBarAll.Visible = false ;
                this.Cursor = Cursors.Default;
            }
        }

        private void ExportMif()
        {          
            try
            {
                progressBarSub.Visible = true;
                progressBarAll.Visible = true;
                this.Cursor = Cursors.WaitCursor;
                IGeometry pGeometry = null;
                IFeatureLayer pFeatureLayer = null;
                string strFilter, strTargetFileName;
                E00DwgExport pE00Ep = new E00DwgExport();


                List<IFeatureLayer> pLayers= GetCheckLayers();
                if (pLayers.Count == 0)
                {
                    MsgHelper.ShowWarningMsgbox("未选择要导出的图层！");
                    return;
                }
                IFeatureClass pFclsClip = null;
                if (chkAll.Checked)
                {
                    pGeometry = null;
                    pE00Ep.Clip = false;
                }
                else
                {
                    if (tabControl2.SelectedTab.Text == "按图幅范围")
                    {
                        if (chooseTuFu2.TuFus.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
                            return;
                        }
                        if (!chkEpByTufu.Checked )
                        {
                            var v = from o in chooseTuFu2.TuFus select o.Geometry;
                            pGeometry = GeometryHelper.Union(v.ToList()) as IPolygon;

                        }
                    }
                    else if (tabControl2.SelectedTab.Text == "按自定义范围")
                    {
                        if (pPolygonCustom == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
                            return;
                        }
                        pGeometry = pPolygonCustom;                       
                    }
                    else if (tabControl2.SelectedTab.Text == "按测区范围")
                    {
                        if (chooseFWX2.PolygonFWX == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
                            return;
                        }
                        pGeometry = chooseFWX2.PolygonFWX;
                    }
                    else if (tabControl2.SelectedTab.Text == "按行政区范围")
                    {
                        pGeometry = selectXZQ1.GetGeometry();
                        if (pGeometry == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
                            return;
                        }
                    }
                }               
                ESRI.ArcGIS.Geoprocessor.Geoprocessor GP = null;
                ESRI.ArcGIS.DataInteroperabilityTools.QuickExport pQuickEpTool = null;
                pQuickEpTool= new ESRI.ArcGIS.DataInteroperabilityTools.QuickExport();      
                pE00Ep.Path = txtExportPath.Text;
                pE00Ep.Clip = chkCut.Checked;
                pE00Ep.SetProcessBarCurrent = setSubPgbCurrent;
                pE00Ep.SetProcessBarMax = setSubPgbMax;
               // IScratchWorkspaceFactory pScratchWksFac = new ESRI.ArcGIS.DataSourcesGDB.FileGDBScratchWorkspaceFactory();
               // pE00Ep.TempFeatureWorkspace = pScratchWksFac.DefaultScratchWorkspace as IFeatureWorkspace;
                IFeatureWorkspace pFks = CreateGdbWks(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "E00Temp.gdb");
                pE00Ep.TempFeatureWorkspace = pFks;    
                if (pGeometry != null &&  chkCut.Checked )
                {
                    pFclsClip = CreateClipFeatureClass(pE00Ep.TempFeatureWorkspace, pGeometry, (m_Application.Document as IMxDocument ).ActiveView.FocusMap.SpatialReference);
                }
                progressBarAll.Value = 0;
                progressBarAll.Maximum = pLayers.Count;
                for (int i = 0; i < pLayers.Count; i++)
                {
                   
                        if (GP == null) GP = new ESRI.ArcGIS.Geoprocessor.Geoprocessor();
                        GP.OverwriteOutput = true;
                        GP.AddOutputsToMap = false;
                        GP.LogHistory = true;
                        pFeatureLayer = pLayers[i] ;
                        IFeatureClass pFeatCls;
                        pFeatCls = pFeatureLayer.FeatureClass;                        
                        LogHelper.WriteLog("正在导出图层'" + pFeatureLayer.Name + "'");
                        pE00Ep.FeatureLayer = pFeatureLayer;
                        strTargetFileName = dataGridViewByMap.Rows[i].Cells[2].Value == null ? pFeatureLayer.Name : dataGridViewByMap.Rows[i].Cells[2].Value.ToString();
                        strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
                        if (tabControl2.SelectedTab.Text == "按图幅范围" && chkEpByTufu.Checked )
                        {
                            System.Windows.Forms.Application.DoEvents();
                            progressBarSub.Value = 0;
                            progressBarSub.Maximum = chooseTuFu2.TuFus.Count;
                            DirectoryInfo dir = new DirectoryInfo(txtExportPath.Text);
                            for (int j = 0; j < chooseTuFu2.TuFus.Count; j++)
                            {
                                LogHelper.WriteLog("开始导出图幅'" + chooseTuFu2.TuFus[j].Code + "'内的选择的图层数据");
                                if (chkCut.Checked)
                                {
                                    pE00Ep.FeatureClassClip = CreateClipFeatureClass(pE00Ep.TempFeatureWorkspace, ((ESRI.ArcGIS.esriSystem.IClone)chooseTuFu2.TuFus[j].Geometry).Clone() as IGeometry, (m_Application.Document as IMxDocument).ActiveView.FocusMap.SpatialReference);
                                }
                                dir.CreateSubdirectory(chooseTuFu2.TuFus[j].Code);
                                pE00Ep.Path = txtExportPath.Text + "\\" + chooseTuFu2.TuFus[j].Code;
                                pE00Ep.FilterGeometry = chooseTuFu2.TuFus[j].Geometry;
                                pE00Ep.Filter = strFilter;
                                pE00Ep.TargetFileName = strTargetFileName;
                                if (pE00Ep.ExportMif(GP, pQuickEpTool))
                                {
                                    LogHelper.WriteLog("图幅" + chooseTuFu2.TuFus[j].Code + "'内图层'" + pFeatureLayer.Name + "'导出成功");
                                }
                                else
                                {
                                    LogHelper.WriteLog("图幅" + chooseTuFu2.TuFus[j].Code + "'内图层'" + pFeatureLayer.Name + "'导出失败");
                                }
                               // ((IDataset)pE00Ep.FeatureClassClip).Delete();
                                if (chkCut.Checked)
                                {
                                    try
                                    {
                                        ((IDataset)pE00Ep.FeatureClassClip).Delete();
                                        pE00Ep.FeatureClassClip = null;
                                    }
                                    catch (System.Exception) { }
                                }
                                progressBarSub.Value++;
                            }
                            
                        }
                        else
                        {
                            pE00Ep.FeatureClassClip = pFclsClip;
                            pE00Ep.FilterGeometry = pGeometry;
                            pE00Ep.Filter = strFilter;
                            pE00Ep.TargetFileName = strTargetFileName;
                            bool bln=pE00Ep.ExportMif(GP, pQuickEpTool);
                            if (bln)
                            {
                                LogHelper.WriteLog("图层'" + pFeatureLayer.Name + "'导出成功");
                            }
                            else
                            {
                                LogHelper.WriteLog("图层'" + pFeatureLayer.Name + "'导出失败");
                            }
                           // ((IDataset)pE00Ep.FeatureClassClip).Delete();
                        }

                        progressBarAll.Value++;
                        System.Windows.Forms.Application.DoEvents();
                    }
                
                if (pE00Ep.FeatureClassClip != null)
                {
                    try
                    {
                        ((IDataset)pE00Ep.FeatureClassClip).Delete();
                        pE00Ep.FeatureClassClip = null;
                    }
                    catch (System.Exception) { }
                }
                //((IDataset)pFks).Delete();
                LogHelper.WriteLog("导出完毕");
                MsgHelper.ShowInfomationMsgbox("导出完毕！");
            }
            catch (System.Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
            }
            finally
            {
                progressBarSub.Visible = false;
                progressBarAll.Visible = false;
                this.Cursor = Cursors.Default;
            }
        }
        
        //private void ExportDwg_old()
        //{
            
        //    Autodesk.AutoCAD.Interop.IAcadApplication pAcadApplication = null;
        //    progressBarSub.Visible = true;
        //    progressBarAll.Visible = true;
        //    this.Enabled = false ;
        //    System.Diagnostics.Process pProcessNew = null;

        //    try
        //    {
        //        string strExePath;
        //        if (!DwgExportUtility.CheckCadInstall(out strExePath ))
        //        {
        //            MsgHelper.ShowWarningMsgbox("系统检测到您的电脑上未安装AutoCAD2007以上版本的软件！");
        //            return;
        //        }
        //        List<IFeatureLayer> pLayers = GetCheckLayers();
        //        if (pLayers.Count == 0)
        //        {
        //            MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
        //            return;
        //        }
                
        //        this.Cursor = Cursors.WaitCursor;                
        //       // pAcadApplication = new Autodesk.AutoCAD.Interop.AcadApplicationClass();

        //        System.Diagnostics.Process[] pProcessCollection= System.Diagnostics.Process.GetProcessesByName("acad");

        //        System.Diagnostics.ProcessStartInfo pProcessInfo = new System.Diagnostics.ProcessStartInfo(strExePath);
        //        pProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //        System.Diagnostics.Process pCadProcess = System.Diagnostics.Process.Start(pProcessInfo);
        //        pCadProcess.WaitForInputIdle();
        //        System.Diagnostics.Process[] pProcessCollection2 = System.Diagnostics.Process.GetProcessesByName("acad");
                
        //        foreach (System.Diagnostics.Process p in pProcessCollection2)
        //        {
        //            bool blnFound = false;
        //            foreach (System.Diagnostics.Process p2 in pProcessCollection)
        //            {
        //                if (p.Id  == p2.Id )
        //                {
        //                    blnFound = true;
        //                    break;
        //                }
        //            }
        //            if (!blnFound)
        //            {
        //                pProcessNew = p;
        //                break;
        //            }
        //        }
        //        //while (pCadProcess.MainWindowHandle == IntPtr.Zero)
        //        //{
        //        //    System.Threading.Thread.Sleep(1000);
        //        //    pCadProcess.Refresh();
        //        //}
              
        //        while (pAcadApplication == null)
        //        {
        //            try
        //            {
        //                pAcadApplication = (Autodesk.AutoCAD.Interop.IAcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
        //                System.Threading.Thread.Sleep(1000);
        //            }
        //            catch (Exception ex)
        //            {
                      
        //                Application.DoEvents();
        //            }
        //        }



        //       // pAcadApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.17") as Autodesk.AutoCAD.Interop.IAcadApplication;
                
        //       // object obj = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.17");
        //       // pAcadApplication.Visible = false;                       
             
        //        IFeatureLayer pFeatureLayer = null;
        //        string strFilter, strTargetFileName;
        //        List<IFeatureLayer> pFeatureLayerList = new List<IFeatureLayer>();
        //        List<string> pFilterList = new List<string>();
        //        for (int i = dataGridViewByMap.Rows.Count-1; i >=0; i--)
        //        {
        //            if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
        //            {
        //                pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
        //                pFeatureLayerList.Add(pFeatureLayer);
        //                strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
        //                pFilterList.Add(strFilter);
        //            }                   
        //        }
        //        logPanel.ClearLog();
                
        //        E00DwgExport pE00DwgEp = new E00DwgExport();
        //        pE00DwgEp.CadFcodeTable = OpenCadFcodeTable();
        //        pE00DwgEp.Path = txtExportPath.ControlText;
        //        pE00DwgEp.Clip = chkCut.Checked;
        //        //IFeatureWorkspace pTmpWks = CreateGdbWks(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "E00Temp.gdb");
        //        //pE00DwgEp.TempFeatureWorkspace = pTmpWks;
        //        pE00DwgEp.WriteLog = LogHelper.WriteLog;
        //        pE00DwgEp.SetProcessBarCurrent = setAllPgbCurrent;
        //        pE00DwgEp.SetProcessBarMax = setAllPgbMax;
        //        if (!chkAll.Checked)
        //        {
        //            if (tabControl2.SelectedTab.Text == "按图幅范围")
        //            {
        //                if (chooseTuFu2.TuFus.Count == 0)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
        //                    return;
        //                }
        //                if (chkEpByTufu.Checked == false)
        //                {
        //                    LogHelper.WriteLog("开始导出选择的图幅范围内的选择的图层数据");
        //                    pE00DwgEp.FilterGeometry = TuFuUtility.GetSelectTuFuRegionByList(chooseTuFu2.TuFus);// UnionTfGeometry(chooseTuFu2.TuFus);                                             
        //                    pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                    pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                    pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                }
        //                else
        //                {
        //                    progressBarAll.Value = 0;
        //                    progressBarAll.Maximum = chooseTuFu2.TuFus.Count;
        //                    foreach (TuFu pTufu in chooseTuFu2.TuFus)
        //                    {
        //                        LogHelper.WriteLog("开始导出图幅'" + pTufu.TuFuName + "'内的选择的图层数据");
        //                        pE00DwgEp.FilterGeometry = pTufu.Geometry;
        //                        if (System.IO.Directory.Exists(txtExportPath.ControlText))
        //                        {
        //                            pE00DwgEp.Path = txtExportPath.ControlText;
        //                        }
        //                        else
        //                        {
        //                            string strPath = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                            if (System.IO.Directory.Exists(strPath ) == false)
        //                            {
        //                                LogHelper.WriteLog("导出路径设置不正确！");
        //                                return;
        //                            }
        //                            pE00DwgEp.Path = strPath;
        //                        }

                               
        //                        pE00DwgEp.TargetFileName = pTufu.TuFuName;
        //                        pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                        Application.DoEvents();
        //                        progressBarAll.Value++;
        //                    }
        //                }
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按自定义范围")
        //            {
        //                if (pPolygonCustom == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = pPolygonCustom;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按测区范围")
        //            {
        //                if (chooseFWX2.PolygonFWX == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的测区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = chooseFWX2.PolygonFWX;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按行政区范围")
        //            {
        //                if (selectXZQ1.GetGeometry () == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = selectXZQ1.GetGeometry();
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //        }
        //        else
        //        {
        //            LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
        //            pE00DwgEp.FilterGeometry = null;
        //            pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText );
        //            pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //            pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //        }
        //        LogHelper.WriteLog("导出完毕");
        //        MsgHelper.ShowInfomationMsgbox("导出完毕！");
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
        //    }
        //    finally
        //    {
        //        this.Enabled = true;
        //        progressBarSub.Visible = false ;
        //        progressBarAll.Visible = false ;
        //        this.Cursor = Cursors.Default;
                
        //        try
        //        {
        //            if (pAcadApplication != null)
        //            {

        //                pAcadApplication.Visible = true;
        //            }
        //            if (pProcessNew != null && pProcessNew.HasExited==false )
        //            {

        //                pProcessNew.Kill();
        //            }
        //        }
        //        catch (System.Exception) { }
                
        //    }

        //    SetCadVisible();
        //}
        //private void ExportDwg()
        //{           
        //    progressBarSub.Visible = true;
        //    progressBarAll.Visible = true;
        //    this.Enabled = false;
        //    DWGdirect.Runtime.Services cadService=null;
        //    try
        //    {               
        //        List<IFeatureLayer> pLayers = GetCheckLayers();
        //        if (pLayers.Count == 0)
        //        {
        //            MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
        //            return;
        //        }
        //        this.Cursor = Cursors.WaitCursor;                               
        //        IFeatureLayer pFeatureLayer = null;
        //        string strFilter, strTargetFileName;
        //        List<IFeatureLayer> pFeatureLayerList = new List<IFeatureLayer>();
        //        List<string> pFilterList = new List<string>();
        //        for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
        //        {
        //            if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
        //            {
        //                pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
        //                pFeatureLayerList.Add(pFeatureLayer);
        //                strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
        //                pFilterList.Add(strFilter);
        //            }
        //        }
        //        logPanel.ClearLog();
        //        cadService = new DWGdirect.Runtime.Services();
        //        E00DwgExport pE00DwgEp = new E00DwgExport();
        //        pE00DwgEp.CadFcodeTable = OpenCadFcodeTable();
        //        pE00DwgEp.Path = txtExportPath.ControlText;
        //        pE00DwgEp.Clip = chkCut.Checked;
              
        //        pE00DwgEp.WriteLog = LogHelper.WriteLog;
        //        pE00DwgEp.SetProcessBarCurrent = setAllPgbCurrent;
        //        pE00DwgEp.SetProcessBarMax = setAllPgbMax;
        //        if (!chkAll.Checked)
        //        {
        //            if (tabControl2.SelectedTab.Text == "按图幅范围")
        //            {
        //                if (chooseTuFu2.TuFus.Count == 0)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
        //                    return;
        //                }
        //                if (chkEpByTufu.Checked == false)
        //                {
        //                    LogHelper.WriteLog("开始导出选择的图幅范围内的选择的图层数据");
        //                    pE00DwgEp.FilterGeometry = TuFuUtility.GetSelectTuFuRegionByList(chooseTuFu2.TuFus);// UnionTfGeometry(chooseTuFu2.TuFus);                                             
        //                    pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                    pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                    pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                }
        //                else
        //                {
        //                    progressBarAll.Value = 0;
        //                    progressBarAll.Maximum = chooseTuFu2.TuFus.Count;
        //                    foreach (TuFu pTufu in chooseTuFu2.TuFus)
        //                    {
        //                        LogHelper.WriteLog("开始导出图幅'" + pTufu.TuFuName + "'内的选择的图层数据");
        //                        pE00DwgEp.FilterGeometry = pTufu.Geometry;
        //                        if (System.IO.Directory.Exists(txtExportPath.ControlText))
        //                        {
        //                            pE00DwgEp.Path = txtExportPath.ControlText;
        //                        }
        //                        else
        //                        {
        //                            string strPath = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                            if (System.IO.Directory.Exists(strPath) == false)
        //                            {
        //                                LogHelper.WriteLog("导出路径设置不正确！");
        //                                return;
        //                            }
        //                            pE00DwgEp.Path = strPath;
        //                        }


        //                        pE00DwgEp.TargetFileName = pTufu.TuFuName;
        //                        pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //                        Application.DoEvents();
        //                        progressBarAll.Value++;
        //                    }
        //                }
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按自定义范围")
        //            {
        //                if (pPolygonCustom == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = pPolygonCustom;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按测区范围")
        //            {
        //                if (chooseFWX2.PolygonFWX == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的测区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = chooseFWX2.PolygonFWX;
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //            else if (tabControl2.SelectedTab.Text == "按行政区范围")
        //            {
        //                if (selectXZQ1.GetGeometry() == null)
        //                {
        //                    MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
        //                    return;
        //                }
        //                LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
        //                pE00DwgEp.FilterGeometry = selectXZQ1.GetGeometry();
        //                pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //                pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //                pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //            }
        //        }
        //        else
        //        {
        //            LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
        //            pE00DwgEp.FilterGeometry = null;
        //            pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.ControlText);
        //            pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.ControlText);
        //            pE00DwgEp.ExportDwg( pFeatureLayerList, pFilterList);
        //        }
        //        LogHelper.WriteLog("导出完毕");
        //        MsgHelper.ShowInfomationMsgbox("导出完毕！");
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
        //    }
        //    finally
        //    {
        //        if (cadService != null) cadService.Dispose();
        //        this.Enabled = true;
        //        progressBarSub.Visible = false;
        //        progressBarAll.Visible = false;
        //        this.Cursor = Cursors.Default;              
        //    }          
        //}

        /// <summary>
        /// 
        /// </summary>
        private void ExportDwg()
        {
            //ComObject pAcadApplication2 = ComObject.CreateComInstance("AutoCAD.Application");
            //ComObject pAcadColor = ComObject.CreateInstance(pAcadApplication2.InvokeMethod("GetInterfaceObject", "AutoCAD.AcCmColor.17"));
            //pAcadApplication2["Visible"] = false ;
            Autodesk.AutoCAD.Interop.IAcadApplication pAcadApplication = null;
            progressBarSub.Visible = true;
            progressBarAll.Visible = true;
            this.Enabled = false;
            System.Diagnostics.Process pProcessNew = null;

            try
            {
                string strExePath;
                if (!DwgExportUtility.CheckCadInstall(out strExePath))
                {
                    MsgHelper.ShowWarningMsgbox("系统检测到您的电脑上未安装AutoCAD2007以上版本的软件！");
                    return;
                }
                List<IFeatureLayer> pLayers = GetCheckLayers();
                if (pLayers.Count == 0)
                {
                    MsgHelper.ShowInfomationMsgbox("未选择要导出的图层！");
                    return;
                }

                this.Cursor = Cursors.WaitCursor;
                // pAcadApplication = new Autodesk.AutoCAD.Interop.AcadApplicationClass();

                System.Diagnostics.Process[] pProcessCollection = System.Diagnostics.Process.GetProcessesByName("acad");

                System.Diagnostics.ProcessStartInfo pProcessInfo = new System.Diagnostics.ProcessStartInfo(strExePath);
                pProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                System.Diagnostics.Process pCadProcess = System.Diagnostics.Process.Start(pProcessInfo);
                pCadProcess.WaitForInputIdle();
                System.Diagnostics.Process[] pProcessCollection2 = System.Diagnostics.Process.GetProcessesByName("acad");

                foreach (System.Diagnostics.Process p in pProcessCollection2)
                {
                    bool blnFound = false;
                    foreach (System.Diagnostics.Process p2 in pProcessCollection)
                    {
                        if (p.Id == p2.Id)
                        {
                            blnFound = true;
                            break;
                        }
                    }
                    if (!blnFound)
                    {
                        pProcessNew = p;
                        break;
                    }
                }
                //while (pCadProcess.MainWindowHandle == IntPtr.Zero)
                //{
                //    System.Threading.Thread.Sleep(1000);
                //    pCadProcess.Refresh();
                //}

                while (pAcadApplication == null)
                {
                    try
                    {
                        pAcadApplication = (Autodesk.AutoCAD.Interop.IAcadApplication)Marshal.GetActiveObject("AutoCAD.Application");
                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(ex);
                        Application.DoEvents();
                    }
                }



                // pAcadApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.17") as Autodesk.AutoCAD.Interop.IAcadApplication;

                // object obj = System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application.17");
                // pAcadApplication.Visible = false;                       

                IFeatureLayer pFeatureLayer = null;
                string strFilter;
                List<IFeatureLayer> pFeatureLayerList = new List<IFeatureLayer>();
                List<string> pFilterList = new List<string>();
                for (int i = dataGridViewByMap.Rows.Count - 1; i >= 0; i--)
                {
                    if (Convert.ToBoolean(dataGridViewByMap.Rows[i].Cells[0].Value) == true && dataGridViewByMap.Rows[i].Tag is IFeatureLayer)
                    {
                        pFeatureLayer = dataGridViewByMap.Rows[i].Tag as IFeatureLayer;
                        pFeatureLayerList.Add(pFeatureLayer);
                        strFilter = dataGridViewByMap.Rows[i].Cells[3].Value == null ? "" : dataGridViewByMap.Rows[i].Cells[3].Value.ToString();
                        pFilterList.Add(strFilter);
                    }
                }
               

                E00DwgExport pE00DwgEp = new E00DwgExport();
                pE00DwgEp.CadFcodeTable = OpenCadFcodeTable();
                pE00DwgEp.Path = txtExportPath.Text;
                pE00DwgEp.Clip = chkCut.Checked;
                //IFeatureWorkspace pTmpWks = CreateGdbWks(Application.StartupPath, "E00Temp.gdb");
                //pE00DwgEp.TempFeatureWorkspace = pTmpWks;
               
                pE00DwgEp.SetProcessBarCurrent = setAllPgbCurrent;
                pE00DwgEp.SetProcessBarMax = setAllPgbMax;
                if (!chkAll.Checked)
                {
                    if (tabControl2.SelectedTab.Text == "按图幅范围")
                    {
                        if (chooseTuFu2.TuFus.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择图幅进行导出！");
                            return;
                        }
                        if (chkEpByTufu.Checked == false)
                        {
                            LogHelper.WriteLog("开始导出选择的图幅范围内的选择的图层数据");
                            var v = from o in chooseTuFu2.TuFus select o.Geometry;
                            pE00DwgEp.FilterGeometry = GeometryHelper.Union(v.ToList());
                            pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.Text);
                            pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.Text);
                            pE00DwgEp.ExportDwg(pAcadApplication, pFeatureLayerList, pFilterList);
                        }
                        else
                        {
                            progressBarAll.Value = 0;
                            progressBarAll.Maximum = chooseTuFu2.TuFus.Count;
                            foreach (Mapsheet pTufu in chooseTuFu2.TuFus)
                            {
                                LogHelper.WriteLog("开始导出图幅'" + pTufu.Code + "'内的选择的图层数据");
                                pE00DwgEp.FilterGeometry = pTufu.Geometry;
                                if (System.IO.Directory.Exists(txtExportPath.Text))
                                {
                                    pE00DwgEp.Path = txtExportPath.Text;
                                }
                                else
                                {
                                    string strPath = System.IO.Path.GetDirectoryName(txtExportPath.Text);
                                    if (System.IO.Directory.Exists(strPath) == false)
                                    {
                                        LogHelper.WriteLog("导出路径设置不正确！");
                                        return;
                                    }
                                    pE00DwgEp.Path = strPath;
                                }


                                pE00DwgEp.TargetFileName = pTufu.Code;
                                pE00DwgEp.ExportDwg(pAcadApplication, pFeatureLayerList, pFilterList);
                                Application.DoEvents();
                                progressBarAll.Value++;
                            }
                        }
                    }
                    else if (tabControl2.SelectedTab.Text == "按自定义范围")
                    {
                        if (pPolygonCustom == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未定义范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出自定义范围内的选择的图层数据");
                        pE00DwgEp.FilterGeometry = pPolygonCustom;
                        pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.Text);
                        pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.Text);
                        pE00DwgEp.ExportDwg(pAcadApplication, pFeatureLayerList, pFilterList);
                    }
                    else if (tabControl2.SelectedTab.Text == "按测区范围")
                    {
                        if (chooseFWX2.PolygonFWX == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择测区范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出选择的测区范围内的选择的图层数据");
                        pE00DwgEp.FilterGeometry = chooseFWX2.PolygonFWX;
                        pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.Text);
                        pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.Text);
                        pE00DwgEp.ExportDwg(pAcadApplication, pFeatureLayerList, pFilterList);
                    }
                    else if (tabControl2.SelectedTab.Text == "按行政区范围")
                    {
                        if (selectXZQ1.GetGeometry() == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择行政区范围进行导出！");
                            return;
                        }
                        LogHelper.WriteLog("开始导出选择的行政区范围内的选择的图层数据");
                        pE00DwgEp.FilterGeometry = selectXZQ1.GetGeometry();
                        pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.Text);
                        pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.Text);
                        pE00DwgEp.ExportDwg(pAcadApplication, pFeatureLayerList, pFilterList);
                    }
                }
                else
                {
                    LogHelper.WriteLog("开始导出全图范围内的选择的图层数据");
                    pE00DwgEp.FilterGeometry = null;
                    pE00DwgEp.Path = System.IO.Path.GetDirectoryName(txtExportPath.Text);
                    pE00DwgEp.TargetFileName = System.IO.Path.GetFileNameWithoutExtension(txtExportPath.Text);
                    pE00DwgEp.ExportDwg(pAcadApplication, pFeatureLayerList, pFilterList);
                }
                LogHelper.WriteLog("导出完毕");
                MsgHelper.ShowInfomationMsgbox("导出完毕！");
            }
            catch (System.Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("导出失败：" + ex.Message);
            }
            finally
            {
                this.Enabled = true;
                progressBarSub.Visible = false;
                progressBarAll.Visible = false;
                this.Cursor = Cursors.Default;

                try
                {
                    if (pAcadApplication != null)
                    {

                        pAcadApplication.Visible = true;
                    }
                    if (pProcessNew != null && pProcessNew.HasExited == false)
                    {

                        pProcessNew.Kill();
                    }
                }
                catch (System.Exception) { }

            }
            SetCadVisible();
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetCadVisible()
        {
            try
            {
                System.Diagnostics.Process[] pProcessCollection = System.Diagnostics.Process.GetProcessesByName("acad");
                foreach (System.Diagnostics.Process p in pProcessCollection)
                {
                    Form frm= Form.FromHandle(p.MainWindowHandle) as Form ;
                    if (frm != null) frm.Visible = true;
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private System.Data.DataTable OpenCadFcodeTable()
        {
            System.Data.DataTable pDataTable = null; ;
            try
            {
                string strFileName =AppConfig.ConfigPath + "\\CadConfig.mdb";
                string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFileName;
                System.Data.OleDb.OleDbConnection pOleDbConnection = new System.Data.OleDb.OleDbConnection();
                pOleDbConnection.ConnectionString = strConnection;
                pOleDbConnection.Open();
                System.Data.OleDb.OleDbCommand pCmd = pOleDbConnection.CreateCommand();
                pCmd.CommandText = "select distinct south_code, fcode,style from features ";
                System.Data.OleDb.OleDbDataAdapter pDataAdapter = new System.Data.OleDb.OleDbDataAdapter(pCmd);
                System.Data.DataSet pDst = new System.Data.DataSet();
                pDataAdapter.Fill(pDst);
                pDataTable = pDst.Tables[0];
                pOleDbConnection.Close();
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return pDataTable;
        }

        private IFeatureWorkspace CreateGdbWks(string strPath, string strName)
        {
            IFeatureWorkspace pFks = null;
            IWorkspaceFactory2 pWksFac = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
            try
            {
                pFks = pWksFac.OpenFromFile(strPath + "\\" + strName, 0) as IFeatureWorkspace;
            }
            catch (System.Exception)
            {
                IWorkspaceName pWksName = pWksFac.Create(strPath, strName, null, 0);
                IName pName = pWksName as IName;
                pFks = pName.Open() as IFeatureWorkspace;
            }
            // IFileNames pFileNameS=new  FileNamesClass();
            //pFileNameS.Add( strName);
            //if (pWksFac.ContainsWorkspace(strPath, pFileNameS))
            //{
            //   IWorkspaceName pWksName= pWksFac.GetWorkspaceName(strPath, pFileNameS);
            //   IName pName = pWksName as IName;
            //   pFks = pName.Open() as IFeatureWorkspace;
            //}
            //else
            //{
            //    IWorkspaceName pWksName= pWksFac.Create(strPath, strName, null, 0);
            //    IName pName = pWksName as IName;
            //    pFks=pName.Open() as IFeatureWorkspace;
            //}
            return pFks;
        }

        /// <summary>
        /// 生成临时的裁切Featureclass
        /// </summary>
        /// <param name="pFwks"></param>
        /// <param name="pPolygon"></param>
        /// <param name="pSpatialRef"></param>
        /// <returns></returns>
        private IFeatureClass CreateClipFeatureClass(IFeatureWorkspace pFwks, IGeometry  pPolygon, ISpatialReference pSpatialRef)
        {
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            geometryDefEdit.SpatialReference_2 = pSpatialRef;
            string strName = "clip";
            string strNewFclsName = strName;
            int index = -1;
            while (true)
            {
                index++;
                if (index == 0)
                {
                    strNewFclsName = strName;
                }
                else
                {
                    strNewFclsName = strName + "_" + index;
                }
                if (((IWorkspace2)pFwks).get_NameExists(esriDatasetType.esriDTFeatureClass, strNewFclsName) == false)
                {
                    break;
                }
            }
            pPolygon.Project(pSpatialRef);
            IFeatureClass pFcls = pFwks.CreateFeatureClass(strNewFclsName, fields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
            IFeature pFeature = pFcls.CreateFeature();

            IZAware pZArare = pPolygon as IZAware;
            pZArare.ZAware = false ;
            //IZ pZ = pPolygon as IZ;
            //if (pZ != null) pZ.SetConstantZ(0);

            pFeature.Shape = pPolygon;
            pFeature.Store();
            return pFcls;
        }

        #endregion

        private void dataGridViewByMap_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
